package com.ebt.m.wiki;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.data.middle.datatype.EController;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.fragment.LazyFragment;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.data.middle.util.InsuranceFieldUtil;
import com.ebt.m.data.middle.InsuranceObj;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.wiki.util.AgeObj;
import com.ebt.m.wiki.util.AgeUnitEnum;
import com.ebt.m.wiki.util.WikiUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author
 * @description 产品-投保规则
 */
public class FrgProductRule extends LazyFragment {
    private Context mContext;
    private View mainView;
    private TableLayout container;
    private View area_rule;
    private WebView web_rule;


    private ProductBridgeObj mProductObj;
    private InsuranceObj mInsuranceObj;
    private ProductInfo mProductInfo;

    public static FrgProductRule newInstance(ProductBridgeObj mProductObj) {
        FrgProductRule frg = new FrgProductRule();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", mProductObj);
        frg.setArguments(bundle);
        return frg;
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.wiki_frg_product_rule, null);
        mContext = inflater.getContext();
        initView(mainView);
        initData();
        initListener();
        setContentView(mainView);
        onDataSyncPost();
//        return mainView;
    }

    private void initView(View view) {
        container = (TableLayout) view.findViewById(R.id.container);
        area_rule = view.findViewById(R.id.area_rule);
        web_rule = (WebView) view.findViewById(R.id.web_rule);
        area_rule.setVisibility(View.GONE);
    }

    private void initData() {
        Bundle bundle = getArguments();
        this.mProductObj = (ProductBridgeObj) bundle.getSerializable("data");
        this.mInsuranceObj = mProductObj.getInsuranceObj();
        this.mProductInfo = mProductObj.getmProduct();
        generateTable();
        setWebViewPara();
        setRule();
    }

    /**
     * <item>产品名称</item>
     * <item>险种类别</item>
     * <item>发布日期</item>
     * <item>分红属性</item>
     * <item>合同属性</item>
     * <item>组合属性</item>
     * <item>保障期间</item>
     * <item>缴费期间</item>
     * <item>投保性别</item>
     * <item>投保职业</item>
     * <item>投保年龄</item>
     */
    private void generateTable() {
        Observable
                .just("")
                .map(s -> {
                    String[] keys = mContext.getResources().getStringArray(R.array.wiki_rule_key);
                    List<RuleKV> list = new ArrayList<RuleKV>();
                    if (keys != null) {
                        RuleKV rkv = new RuleKV(keys[0], mProductInfo.Name);
                        list.add(rkv);
                        rkv = new RuleKV(keys[1], mProductInfo.CategoryName);
                        list.add(rkv);
                        //FIXME 20170518按后台要求隐藏
//                        rkv = new RuleKV(keys[2], mProductInfo.RecordTime);
//                        list.add(rkv);
                        rkv = new RuleKV(keys[3], mProductInfo.Fenhongxingzhi == 1 ? "分红型" : "非分红型");
                        list.add(rkv);
                        rkv = new RuleKV(keys[4], mProductInfo.getContractPropertyStr(mProductInfo.ContractProperty));//合同属性
                        list.add(rkv);
                        rkv = new RuleKV(keys[5], mProductInfo.getCompositionPropertyStr(mProductInfo.CompositionProperty));
                        list.add(rkv);
                        rkv = new RuleKV(keys[6], getStrPropertys(InsuranceFieldUtil.FIELDNAME_COVERAGEPERIOD));//保障期间
                        list.add(rkv);
                        rkv = new RuleKV(keys[7], getStrPropertys(InsuranceFieldUtil.FIELDNAME_PAYMENTPERIOD));//缴费期间
                        list.add(rkv);
                        rkv = new RuleKV(keys[8], mProductInfo.getAccSexStr2(mProductInfo.AccSex));
                        list.add(rkv);
                        rkv = new RuleKV(keys[9], mProductInfo.getCareerCategoryCn(mProductInfo.AccOccupation) + "类以内可");//职业类别
                        list.add(rkv);
                        AgeObj ao = AgeObj.parseAgeObj(mProductInfo.MinAge);
                        String min = ao.getAge() + getAgeUnit(ao);
                        ao = AgeObj.parseAgeObj(mProductInfo.MaxAge);
                        String max = ao.getAge() + getAgeUnit(ao);
                        rkv = new RuleKV(keys[10], min + "-" + max);
                        list.add(rkv);
                    }
                    return list;
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(list -> {
                    container.removeAllViews();
                    TableRow row = null;
                    for (int i = 0; i < list.size(); i++) {
                        row = (TableRow) LayoutInflater.from(mContext).inflate(R.layout.wiki_frg_product_rule_row, null, true);
                        TextView txtK = (TextView) row.findViewById(R.id.txt_key);
                        TextView txtV = (TextView) row.findViewById(R.id.txt_value);
                        txtK.setText(list.get(i).key);
                        txtV.setText(list.get(i).value);
                        if (i == list.size() - 1) {
                            txtK.setBackgroundResource(R.drawable.shape_white_stroke_cornor_lb);
                            txtV.setBackgroundResource(R.drawable.shape_with_stroke_cornor_rb);
                        } else {
                            txtK.setBackgroundResource(R.drawable.shape_white_with_stroke);
                            txtV.setBackgroundResource(R.drawable.shape_white_with_stroke);
                        }
                        container.addView(row, i);

                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });

    }

    private String getAgeUnit(AgeObj ao) {
        AgeUnitEnum unitEnum = ao.getUnit();
        String result = "";
        switch (unitEnum) {
            case year:
                result = "岁";
                break;
            case month:
                result = "月";
                break;
            case day:
                result = "天";
                break;
        }
        return result;
    }

    private String getStrPropertys(String fname) {
        String result = "";
        List<PolicyNodeMeta> list = mInsuranceObj.getControllerNode();
        PolicyNodeMeta node = null;
        for (int i = 0; i < list.size(); i++) {
            node = list.get(i);
            if (node.getFieldName().equalsIgnoreCase(fname)) {
                EController eController = (EController) node.getEBTValue();
                String[] strs = eController.getItemDisPlay();
                result = Arrays.toString(strs);
                if (result != null && result.length() > 2) {
                    result = result.substring(1, result.length() - 1);
                }
            }
        }
        return result;
    }

    private void setWebViewPara() {
        WebSettings settings = web_rule.getSettings();
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false); // 显示放大缩小 controler
        settings.setDefaultTextEncodingName("UTF-8");// 设置字符集编码
        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true);// 开启JavaScript支持
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(false);
        //设置 缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        settings.setDomStorageEnabled(true);
    }

    @SuppressLint("JavascriptInterface")
    private void setRule() {
        if (mProductInfo != null && NetUtils.isNetworkAvailable(mContext)) {
            String url = WikiUtils.PRODUCT_URL_PREFIX + mProductInfo.Id + WikiUtils.PRODUCT_RULE_URL_SUFFIX;
            web_rule.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
            web_rule.setWebViewClient(new MyWebViewClient());
            web_rule.loadUrl(url);
        } else {
            area_rule.setVisibility(View.GONE);
        }
    }

    final class MyWebViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        public void onPageFinished(WebView view, String url) {
//            view.loadUrl("javascript:window.local_obj.showSource('document.getElementsByTagName('body')[0].innerHTML');");
            view.loadUrl("javascript:window.local_obj.showSource(''+document.getElementsByTagName('body')[0].innerHTML+'');");
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            view.loadData("", "text/html", "UTF-8");

        }
    }

    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(String html) {
            if (DataValidation.isEmpty(html)) {
                area_rule.post(new Runnable() {
                    @Override
                    public void run() {
                        area_rule.setVisibility(View.GONE);
                    }
                });
            } else if (html.contains("<Code>NoSuchKey</Code>")) {
                area_rule.post(new Runnable() {
                    @Override
                    public void run() {
                        area_rule.setVisibility(View.GONE);
                    }
                });
            } else {
                area_rule.post(new Runnable() {
                    @Override
                    public void run() {
                        area_rule.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    private void initListener() {
    }

    class RuleKV {
        public RuleKV(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public String key;
        public String value;
    }
}
